package main

import (
	"flag"
	"fmt"
	"time"

	"gitee.com/WisdomClassroom/cli/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func main() {
	core.PublicFlag(BuildTag, BuildGo, BuildTime)
	flag.IntVar(&glb.AccountID, "user-account-id", 1, "user account id")
	flag.Parse()

	if core.FlagHelp {
		flag.Usage()
		fmt.Println("To use default or random value, do not pass database parameters")
		return
	}
	if core.FlagVersion {
		core.PublicVersion()
		return
	}

	var token core.Token

	if core.FlagUsePG || core.FlagUseSqlite {
		config := &gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
			},
			Logger: logger.New(
				glb.Logger,
				logger.Config{
					LogLevel: core.GetGormLogLevel(),
					Colorful: false,
				},
			),
		}
		var err error
		if core.FlagUseSqlite {
			glb.DB, err = gorm.Open(sqlite.Open(core.FlagSqliteDB), config)
		} else {
			glb.DB, err = gorm.Open(postgres.Open(models.GetPgSQLConf()), config)
		}
		if err != nil {
			core.PrintPromptWarning("Open database error\n" + err.Error())
			return
		}

		user := models.User{
			AccountID: int32(glb.AccountID),
		}
		err = glb.DB.Where(&user).First(&user).Error
		if err == gorm.ErrRecordNotFound {
			core.PrintPromptWarning("user not found")
			return
		} else if err != nil {
			core.PrintPromptWarning("Query error\n" + err.Error())
			return
		}

		token = core.Token{
			Timestamp: time.Now().Unix(),
			LifeCycle: core.TokenTimeout,
			AccountID: user.AccountID,
			Name:      user.Name.String,
			Gender:    user.Gender.Int32,
			Type:      user.Type.Int32,
		}
	} else {
		token = core.Token{
			Timestamp: time.Now().Unix(),
			LifeCycle: core.TokenTimeout,
			AccountID: int32(glb.AccountID),
			Name:      "NameForTest",
			Gender:    core.UserGenderMan,
			Type:      core.UserTypeTeacher,
		}
	}

	tokenStr := token.PackToken(&core.FlagTokenCert)

	core.PrintPromptInfo(fmt.Sprintf("generate token successfully:\n%s\n", tokenStr))
}
